<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 夺宝模块控制器
 */
class Lottery extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('go_shoplist_model');
        $this->load->model('go_member_go_record_model');
        $this->load->model('bbs_account_model');
        $this->load->model('bbs_user_model');
        $this->load->model('bbs_recharge_model');
        $this->load->library('Alipay');
        //支付宝配置信息
        $this->alipay_config = $this->web_config['ALIPAY'];
    }
    //夺宝商品首页
    function index(){
        
        $this->assign("url",web_url("duoing_list"));
        
        if($this->bbs_userinfo){
            $duo_total = $this->db->query("select * from tan_go_member_go_record where uid = ".$this->bbs_userinfo['user_id']." group by shopid order by id desc")->num_rows();
            $duo_winner_total = $this->db->query("select * from tan_go_shoplist where q_uid = ".$this->bbs_userinfo['user_id']." and q_showtime = 'N' order by id desc")->num_rows();
            $this->assign("duo_data", array("duo_total"=>$duo_total,"duo_winner_total"=>$duo_winner_total));
        }
        //共揭晓商品数
        $totalLucters = $this->db->query("select * from tan_go_shoplist where q_uid is not null and q_showtime = 'N'")->num_rows();
        //夺宝总数
        
        //获取最新揭晓
        $newlists = $this->get_duoed_list();
        //正在夺宝用户
        $luckers = $this->get_user_duoing_list();
        //获取全部商品
        $shops = $this->get_all_shops_list();
        //夺宝问题
        $wendas = $this->relative_wenda();
        //晒单文章
        $arts = $this->relative_article();
        
        $this->assign("luckers_max_second", $newlists[0]['end_time']);
        $this->assign("luckers_max_id", $luckers[0]['buy_id']);
        $this->assign("newlists", $newlists);
        $this->assign("shops", $shops);
        $this->assign("arts", $arts);
        $this->assign("wendas", $wendas);
        $this->assign("luckers", $luckers);
        $this->assign("totalLucters", $totalLucters);
        $this->assign("more_wenda_url",  web_url("wenda"));
        $this->assign("lotter_index",  123);
        $this->display('lottery/index.html');
    }
    //溜溜夺宝说明
    function instructions() {
        $this->display('lottery/instructions.html');
    }
    //商品详情页
    function detail($goods_id){
        $goods_id = decrypt_lottery_id($goods_id);
        $item = $this->go_shoplist_model->get_shoplist_one(array("id"=>$goods_id));
        if(!$item){
            _message("您查找的商品未找到", web_url("lottery"));
        }
        $q_showtime = (isset($item['q_showtime']) && $item['q_showtime'] == 'N') ? 'N' : 'Y';
        if($item['q_end_time']){
            web_redirect("/lottery_finish/".encrypt_lottery_id($goods_id));//正在揭晓中奖者
        }
        
        $sid=$item['sid'];
        $item['_sid'] = encrypt_lottery_id($item['sid']);
        $item['goods_id'] = encrypt_lottery_id($item['id']);
        //参与小伙伴
        $where = "r.shopid = $goods_id and r.shopqishu = $item[qishu]";
        $buyers = $this->db->query("select r.id,r.shopid,r.shopqishu,r.gonumber,r.ip,r.time,u.nickname,u.head_img,r.uid from tan_go_member_go_record r left join tan_users_info u on u.user_id = r.uid where $where order by r.id desc limit 10")->result_array();
        foreach ($buyers as $key=>$val){
            $time = substr($val['time'],0,10);
            $buyers[$key]['time'] = date("Y-m-d H:i:s",$time).substr($val['time'],10,13);
            $buyers[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['uid']));
            $buyers[$key]['record_id'] = encrypt_lottery_record_id($val['id']);
        }
        
        //往期中奖
        $where = "s.qishu < $item[qishu] and s.sid = $sid and s.q_showtime = 'N' and s.q_uid is not null";
        $olds = $this->db->query("select s.id,s.qishu,s.q_user_code,s.q_uid,u.nickname,u.head_img from tan_go_shoplist s left join tan_users_info u on u.user_id = s.q_uid where $where order by s.qishu desc limit 10")->result_array();
        foreach ($olds as $key=>$val){
            //中奖用户信息
            $record = $this->db->query("select time from tan_go_member_go_record where  uid = $val[q_uid] and shopid = $val[id] and shopqishu = $val[qishu] and goucode like '%$val[q_user_code]%'  order by id desc limit 1")->row_array();
            $olds[$key]['time'] = date("Y-m-d H:i:s",substr($record['time'],0,10)).substr($record['time'],10,13);
            //云购次数
            $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$val[q_uid]' and `shopid` = $val[id] and `shopqishu` = '$val[qishu]'")->row_array();
            $olds[$key]['num'] = $user_shop_number['gonumber'];
            $olds[$key]['lottery_url'] = web_url("lottery_finish/".encrypt_lottery_id($val['id']));
            $olds[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['q_uid']));
        }
        
        //推荐商品
        $recommend_goods = $this->get_remmond_goods($item['id'], $sid);
        
        $this->assign("recommend_goods", $recommend_goods);
        $this->assign("olds", $olds);
        $this->assign("buyers", $buyers);
        $this->assign("item", $item);
        $this->display('lottery/detail.html');
    }
    
    //商品完成页面
    function finish($shop_id){
        $shop_id = decrypt_lottery_id($shop_id);
        $item=$this->db->query("select tan_go_shoplist.*,tan_users.username,tan_users_info.nickname,tan_users_info.head_img from `tan_go_shoplist` left join tan_users on tan_users.user_id = tan_go_shoplist.q_uid  left join tan_users_info on tan_users_info.user_id = tan_go_shoplist.q_uid  where tan_go_shoplist.`id`='$shop_id' LIMIT 1")->row_array();
        $item['username'] = name_formart($item['username']);
        if(!$item){
            _message("没有这个商品!");
        }
        if(empty($item['q_end_time']) && $item['q_showtime'] == 'Y'){
            web_redirect("lottery/".encrypt_lottery_id($shop_id));
        }
        
        if(empty($item['q_user_code'])){
            _message("该商品正在进行中...",  web_url("lottery/".encrypt_lottery_id($shop_id)));
        }
        $item['times'] = substr($item['q_end_time'],0,10) - time();
        $item['q_end_time'] = microt($item['q_end_time']);
        $item['space_url'] = web_url("u/".  encrypt_user_id($item['q_uid']));
        //是否已关注用户
        $is_fan = $this->bbs_userinfo ? ($this->bbs_user_model->get_fan_status(array("user_id"=>$item['q_uid'],"followuid"=>$this->bbs_userinfo['user_id'],"is_del"=>1)) ? 1 : 0) : 0;
        $item['is_fan'] = $is_fan;
        //云购中奖者信息
        $q_user = unserialize($item['q_user']);		
        $q_user_code_len = strlen($item['q_user_code']);
        
        //用户云购时间
        $user_shop_time = $this->db->query("select time from `tan_go_member_go_record` where `uid`= '$item[q_uid]' and `shopid` = '$shop_id' and `shopqishu` = '$item[qishu]' and `huode` = '$item[q_user_code]'")->row_array();
        $user_shop_time = microt($user_shop_time['time']);
        $this->assign("user_shop_time", $user_shop_time);
        //获取中奖用户
        if($item['q_showtime'] == 'N'){
            //获取中奖用户本期商品的云购次数
            $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$item[q_uid]' and `shopid` = '$shop_id' and `shopqishu` = '$item[qishu]'")->row_array();
            $user_shop_number = $user_shop_number['gonumber'];
            $this->assign("user_shop_number", $user_shop_number);
            //获取中奖用户本期商品的所有云购码
//            $user_shop_codes_arr = $this->db->query("select goucode from `tan_go_member_go_record` where `uid`= '$item[q_uid]' and `shopid` = '$shop_id' and `shopqishu` = '$item[qishu]'")->result_array();
//            $user_shop_codes = '';
//            foreach($user_shop_codes_arr as $v){
//                $user_shop_codes .= $v['goucode'].',';		
//            }
//            $user_shop_codes = rtrim($user_shop_codes,',');
//            $this->assign("user_shop_codes", $user_shop_codes);
        }
        
        $h=abs(date("H",$item['q_end_time']));
        $i=date("i",$item['q_end_time']);
        $s=date("s",$item['q_end_time']);
        $w=substr($item['q_end_time'],11,3);
        $user_shop_time_add = $h.$i.$s.$w;
        $user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);	
        
        //幸运号码计算的记录信息
        if($item['q_content']){
                $item_q_content = unserialize($item['q_content']);
                $keysvalue = $new_array = array();
                foreach($item_q_content as $k=>$v){
                    $keysvalue[$k] = $v['time'];				
                    $h=date("H",$v['time']);
                    $i=date("i",$v['time']);
                    $s=date("s",$v['time']);	
                    list($timesss,$msss) = explode(".",$v['time']);
                    $item_q_content[$k]['timeadd'] = $h.$i.$s.$msss;
                    $item_q_content[$k]['time_str'] = date("Y-m-d H:i:s",substr($v['time'],0,10)).".".$msss;
                    $item_q_content[$k]['lottery_url'] = web_url("lottery/".encrypt_lottery_id($v['shopid']));
                    $item_q_content[$k]['space_url'] = web_url("u/". encrypt_user_id($v['uid']));
                    $user = $this->db->query("select nickname,head_img from tan_users_info where user_id = $v[uid] order by user_id desc limit 1")->row_array();
                    $item_q_content[$k]['nickname'] = $user['nickname'];
                    $item_q_content[$k]['head_img'] = $user['head_img'];
                }
                arsort($keysvalue);	//asort($keysvalue);正序
                reset($keysvalue);
                foreach ($keysvalue as $k=>$v){
                    $item_q_content[$k]['index'] = sprintf("%03d",$k+1);
                    $new_array[$k] = $item_q_content[$k];
                }			
                $item['q_content'] = $new_array;
        }
        //下一期
        $itemzx=$this->db->query("select * from `tan_go_shoplist` where `sid`='$item[sid]' and `qishu`>'$item[qishu]' order by `qishu` DESC LIMIT 1")->row_array();
        $itemzx['detail_url'] = web_url("lottery/".  encrypt_lottery_id($itemzx['id']));
        //期数显示
        
        //参与小伙伴
        $where = "r.shopid = $item[id] and r.shopqishu = $item[qishu]";
        $buyers = $this->db->query("select r.id,r.shopid,r.shopqishu,r.gonumber,r.ip,r.time,u.nickname,u.head_img,r.uid from tan_go_member_go_record r left join tan_users_info u on u.user_id = r.uid where $where order by r.id desc limit 10")->result_array();
        foreach ($buyers as $key=>$val){
            $time = substr($val['time'],0,10);
            $buyers[$key]['time'] = date("Y-m-d H:i:s",$time).substr($val['time'],10,13);
            $buyers[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['uid']));
            $buyers[$key]['record_id'] = encrypt_lottery_record_id($val['id']);
        }
        //往期中奖
        $where = "s.sid = $item[sid] and s.q_showtime = 'N' and s.q_uid is not null";//s.qishu < $item[qishu] and 
        $olds = $this->db->query("select s.id,s.qishu,s.q_user_code,s.q_uid,u.nickname,u.head_img from tan_go_shoplist s left join tan_users_info u on u.user_id = s.q_uid where $where order by s.qishu desc limit 10")->result_array();
        foreach ($olds as $key=>$val){
            //中奖用户信息
            $record = $this->db->query("select time from tan_go_member_go_record where  uid = $val[q_uid] and shopid = $val[id] and shopqishu = $val[qishu] and goucode like '%$val[q_user_code]%'  order by id desc limit 1")->row_array();
            $olds[$key]['time'] = date("Y-m-d H:i:s",substr($record['time'],0,10)).substr($record['time'],10,13);
            //云购次数
            $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$val[q_uid]' and `shopid` = $val[id] and `shopqishu` = '$val[qishu]'")->row_array();
            $olds[$key]['num'] = $user_shop_number['gonumber'];
            $olds[$key]['lottery_url'] = web_url("lottery_finish/".encrypt_lottery_id($val['id']));
            $olds[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['q_uid']));
        }
        $item['goods_id'] = encrypt_lottery_id($item['id']);
        $item['_sid'] = encrypt_lottery_id($item['sid']);
        $item['q_uid'] = encrypt_user_id($item['q_uid']);
        
        
        //推荐商品
        $recommend_goods = $this->get_remmond_goods($shop_id, $item['sid']);
        
        $this->assign("recommend_goods", $recommend_goods);
        $this->assign("olds", $olds);
        $this->assign("buyers", $buyers);
        $this->assign("next_item", $itemzx);
        $this->assign("item", $item);
        $this->assign('module', "lottery");
        $this->display('lottery/finish.html');
    }
    //最新揭晓页面
    function finish_list(){
        $buys = $this->get_user_duoing_list();
        $this->assign('buys', $buys);
        $this->assign('buys_max_id', $buys[0]['buy_id']);
        $this->assign('module', "lottery");
        $this->display('lottery/newlist.html');
    }
    //夺宝协议
    function agreement(){
        $this->display('lottery/agreement.html');
    }
    
    //购物车商品列表
    function cartlist(){
        if(!$this->bbs_userinfo){
            web_redirect("site/login.html".$this->get_next_request_url());
        }
        $this->Cartlist = _getcookie("CartShop");//只有单个产品
        if(!$this->Cartlist){
            _message("还未选择商品", web_url("lottery"));
        }
        $Cartlist = json_decode(stripslashes($this->Cartlist),true);
        $shopid = 0;
        $cartData = array();
        foreach ($Cartlist as $key=>$val){
            if(is_array($val)){
                $shopid = $key;
                $cartData = $val;
            }
        }
        if($shopid){
            $shoplist = $this->go_shoplist_model->get_shoplist_one(array("id"=>$shopid));
        }
        if(!$shoplist){
            _message("您查找的商品未找到", web_url("lottery"));
        }
        
        if($shoplist['shenyurenshu'] == 0){//商品已被抢光
            _message("手速太慢了，该商品已经抢光啦！", web_url("lottery_finish/".$shopid));
        }
        
        $MoenyCount=0;//商品总价
        $cartData['num'] = $cartData['num'] >= $shoplist['shenyurenshu'] ? $shoplist['shenyurenshu'] : $cartData['num'];
        
        $shoplist['cart_gorenci'] = $cartData['num'] ? $cartData['num'] : 1;//购买人次	
        $MoenyCount += $shoplist['yunjiage'] * $shoplist['cart_gorenci'];//总计
        $shoplist['cart_xiaoji'] = intval($shoplist['yunjiage'] * $cartData['num']);//小计
        $shoplist['cart_shenyu']=$shoplist['zongrenshu']-$shoplist['canyurenshu'];
        $shoplist['detail_url']=  web_url("lottery/".$shopid);
        $shoplist['cart_yunjiage'] = intval($shoplist['yunjiage']);
        $Cartshopinfo = array(
            $shopid =>array(
                'shenyu' => $shoplist['cart_shenyu'],
                'num' => $cartData['num'],
                'money' => $shoplist['yunjiage'],
            ),
            'MoenyCount' => $MoenyCount
        );
        
        $this->assign("cartNum", $cartData['num']);
        $this->assign("shoplist", $shoplist);
        $this->assign("Cartshopinfo", json_encode($Cartshopinfo));
        $this->assign('module', "lottery");
        $this->display("lottery/cartlist.html");
        
    }
    
    //下订单
    function mkorder(){
        if(!$this->bbs_userinfo){
            web_redirect("site/login.html".$this->get_next_request_url());
        }
        $this->Cartlist = _getcookie("CartShop");//只有单个产品
        if(!$this->Cartlist){
            _message("还未选择商品", web_url("lottery"));
        }
        $Cartlist = json_decode(stripslashes($this->Cartlist),true);
        $shopid = 0;
        $cartData = array();
        foreach ($Cartlist as $key=>$val){
            if(is_array($val)){
                $shopid = $key;
                $cartData = $val;
            }
        }
        if($shopid){
            $shoplist = $this->go_shoplist_model->get_shoplist_one(array("id"=>$shopid));
        }
        if(!$shoplist){
            _message("您查找的商品未找到", web_url("lottery"));
        }
        
        if($shoplist['shenyurenshu'] == 0){//商品已被抢光
            _message("手速太慢了，该商品已经抢光啦！", web_url("lottery_finish/".$shopid));
        }
        
        //会员溜珠余额
        $user_bbs_account = $this->bbs_account_model->get(intval($this->bbs_userinfo['user_id']));
        $userMoney = $user_bbs_account['balance'];
        //总价格
        $MoenyCount = 0;
        $shoplist['cart_gorenci'] = $cartData['num'] ? $cartData['num'] : 1;//购买人次	
        $MoenyCount += $shoplist['yunjiage'] * $shoplist['cart_gorenci'];//总计
        $shoplist['cart_xiaoji'] = intval($shoplist['yunjiage'] * $cartData['num']);//小计
        $shoplist['cart_shenyu']=$shoplist['zongrenshu']-$shoplist['canyurenshu'];
        $shoplist['detail_url']=  web_url("lottery/".$shopid);
        $shoplist['cart_yunjiage'] = intval($shoplist['yunjiage']);
        
        $submitcode = uniqid();
        $this->session->set_userdata('submitcode', $submitcode);
        
        $this->assign("submitcode", $submitcode);
        $this->assign("userMoney", $userMoney);
        $this->assign("MoenyCount", $MoenyCount);
        $this->assign("shoplist", $shoplist);
        $this->assign('module', "lottery");
        $this->display("lottery/order.html");
        
    }
    
    //支付提交页面
    function paysubmit(){
        if(!isset($_POST['submit'])){	
            _message("非法请求",  web_url("cart/cartlist"));
        }
        $submitcode = $this->session->userdata('submitcode');
        if(isset($_POST['submitcode'])) {
            if($_POST['submitcode'] == $submitcode && $submitcode){	//避免重复提交		
                $this->session->userdata('submitcode',null);
            }else{				
                _message("请不要重复提交...",  web_url("cart/cartlist"));
            }	
        }else{
            _message("非法请求", web_url("cart/cartlist"));
        }
	
        //验证是否登录
        if(!$this->bbs_userinfo){
            _message("您还未登录，请先登录再操作", web_url("site/login"));
        }
        
        $pay_checkbox = isset($_POST['moneycheckbox']) ? true : false;//是否余额支付	
        $pay_type = isset($_POST['payType']) ? $_POST['payType'] : false;//支付方式
        
        $this->load->library('Pay');
        $pay = new Pay();
        $ok = $pay->init($this->bbs_userinfo['user_id'],"alipay","go_record");
        if($ok !== 'ok'){
            $_COOKIE['CartShop'] = NULL;
            _setcookie("CartShop",null);
            _message($ok, web_url("cart/cartlist"));
        }
        
        $check = $pay->go_pay($pay_checkbox);
        if(!$check){
           _message("商品支付失败!",  web_url("cart/cartlist"));
        }
        if($check){//成功
            _setcookie("CartShop",null);
            web_redirect("cart/paysuccess");
        }
        exit;
    }
    //alipay支付页面前台
    function lottery_alipay_return(){
        if($_GET){
            $out_trade_no = $_GET['out_trade_no'];	//商户订单号
            $dingdaninfo = $this->db->query("select * from `tan_go_member_addmoney_record` where `code` = '$out_trade_no'")->row_array();
            if(!$dingdaninfo || $dingdaninfo['status'] == '未付款'){
                _message("支付失败",web_url("cart/cartlist"));			
            }else{
                if($dingdaninfo['scookies'] == '1'){
                    _setcookie("CartShop",null);
                    _message("支付成功!",  web_url("cart/paysuccess"));
                }else{
                    _message("商品还未购买,请重新购买商品!",web_url("cart/cartlist"));
                }
            }
        }
    }
    
    //alipay支付后台
    function notify(){
        if($_POST){
            //计算得出通知验证结果
            $alipayNotify = new AlipayNotify($this->alipay_config);
            $verify_result = $alipayNotify->verifyNotify();
            if($verify_result){
                
                $out_trade_no = $_POST['out_trade_no'];	//商户订单号
		$trade_no = $_POST['trade_no'];			//支付宝交易号
		$trade_status = $_POST['trade_status'];	//交易状态
                //开始处理及时到账和担保交易订单
                if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
                    $this->db->trans_begin();
                    $dingdaninfo = $this->db->query("select * from `tan_go_member_addmoney_record` where `code` = '$out_trade_no' and `status` = '未付款' for update")->row_array();
                    if(!$dingdaninfo){	echo "fail";exit;}//没有该订单,失败
                    $c_money = intval($dingdaninfo['money']);			
                    $uid = $dingdaninfo['uid'];
                    $time = time();	
                    //更改订单信息
                    $up_q1 = $this->db->query("UPDATE `tan_go_member_addmoney_record` SET `pay_type` = '支付宝', `status` = '已付款' where `id` = '$dingdaninfo[id]' and `code` = '$dingdaninfo[code]'");
                    //更新账户信息
                    $up_q2 = $this->db->query("UPDATE `tan_bbs_account` SET `total` = `total` + $c_money,`balance` = `balance` + $c_money where (`user_id` = '$uid')");	
                    //添加账户明细
                    $up_q3 = $this->db->query("INSERT INTO `tan_go_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '1', '账户', '充值', '$c_money', '$time')");
                    //添加社区账户溜珠明细
                    $this->db->insert("bbs_zhu_detail",array("user_id"=>$uid,"num"=>intval($c_money),"type"=>"充值","style"=>1,"create_time"=>time()));
                    
                    $up_q4 = $this->db->insert_id();
                    
                    //更新社区充值订单信息
                    
                    //商户订单号
                    $out_trade_no = $_POST['out_trade_no'];
                    //支付宝交易号
                    $trade_no = $_POST['trade_no'];
                    //交易状态
                    $trade_status = $_POST['trade_status'];
                    
                    $data = array();
                    $data['trade_nid'] = $trade_no;
                    $data['trade_status'] = $trade_status;
                    $data['update_time'] = time();
                    $this->bbs_recharge_model->update_recharge_order($data,$out_trade_no);
                    
                    if($up_q1 && $up_q2 && $up_q3 && $up_q4){
                        //更新充值订单附表   
                        $this->bbs_recharge_model->update_recharge_list($data,$out_trade_no);
                        
                        $this->db->trans_commit();			
                    }else{
                        $this->db->trans_rollback();
                        echo "fail";exit;
                    }
                    
                    if(empty($dingdaninfo['scookies'])){					
                        echo "success";exit;	//充值完成			
                    }
                    $scookies = unserialize($dingdaninfo['scookies']);
                    $this->load->library('Pay');
                    $pay = new Pay();			
                    $pay->scookie = $scookies;	
                    
                    $ok = $pay->init($uid,"alipay",'go_record');	//云购商品	
                    if($ok != 'ok'){
                        _setcookie('CartShop',NULL);
                        echo "fail";exit;	//商品购买失败			
                    }		
                    
                    $check = $pay->go_pay(1);
                    if($check){
                        $this->db->query("UPDATE `tan_go_member_addmoney_record` SET `scookies` = '1' where `code` = '$out_trade_no' and `status` = '已付款'");
                        _setcookie('CartShop',NULL);
                        echo "success";exit;			
                    }else{
                        echo "fail";exit;
                    }
                }
                
            }else {
                echo "fail";
            }
        }else{
            echo "fail";
        }
    }
    
    //支付成功页面
    function paysuccess(){
        $_COOKIE['CartShop'] = NULL;
        _setcookie("CartShop",null);
        $this->assign('module', "lottery");
        $this->display("lottery/paysuccess.html");
    }
    
    function lottery_shop_get(){
        if(isset($_POST['lottery_shop_get'])){
            $times = 180;
            $gid = isset($_POST['gid']) ? abs(intval($_POST['gid'])) : exit();
            $info = $this->db->query("select id,xsjx_time,q_end_time from `tan_go_shoplist` where `id` ='$gid' and `q_showtime` = 'Y'")->row_array();
            if(!$info){
                    echo "no";exit;
            }
            if($info['xsjx_time']){$info['q_end_time'] = $info['q_end_time']+$times;}
            $q_time =  intval(substr($info['q_end_time'],0,10));
            if($q_time <= time()){
                    $this->db->query("update `tan_go_shoplist` SET `q_showtime` = 'N' where `id` = '$info[id]' and `q_showtime` = 'Y' and `q_uid` is not null");
            }
            echo $q_time - time();			
            exit;						
        }
    }
    
    /*********ajax异步调用区start*********/
    function ajax_usre_duo_list(){
        if($_POST){
            $buyId = isset($_POST['buyId']) ? trim($_POST['buyId']) : time();
            $buyId = decrypt_lottery_record_id($buyId);
            $list = $this->get_user_duoing_list($buyId);
            $mess['reqStatus'] = true;
            $mess['count'] = count($list);
            $mess['data'] = $list;
            echo JSON($mess);exit;
        }
    }
    //设置获奖商品的状态
    function ajax_shop_set(){
        if(isset($_POST['lottery_sub'])){
            $times = 180;
            $gid = isset($_POST['gid']) ? abs(intval($_POST['gid'])) : exit();
            $gid = decrypt_lottery_id($gid);
            $info = $this->db->query("select s.id,s.q_uid,s.q_user,s.q_end_time,s.q_user_code,s.qishu,u.head_img,u.nickname from tan_go_shoplist s left join tan_users_info u on u.user_id = s.q_uid where s.id = $gid")->row_array();
            
            if(!$info || empty($info['q_end_time'])){
                echo '0';exit;
            }		
            if($info['xsjx_time']){$info['q_end_time'] = $info['q_end_time']+$times;}
            $times =  str_ireplace(".","",$info['q_end_time']);
            $q_time = substr($info['q_end_time'],0,10);
            $q = false;
            if(time() >= $q_time){
                $q = $this->db->query("update `tan_go_shoplist` SET `q_showtime` = 'N' where `id` = '$gid' and `q_showtime` = 'Y' and `q_uid` is not null");	
            }
            if($_POST['resp']){
                $data = array();
                $data['luck_code'] = $info['q_user_code'];
                $data['head_img'] = $info['head_img'];
                $data['nickname'] = $info['nickname'];
                $data['time'] = $this->set_time_two($q_time);
                $data['space_url'] = web_url("u/".encrypt_user_id($info['q_uid']));
                //获奖用户本期总参与数
                $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$info[q_uid]' and `shopid` = '$info[id]' and `shopqishu` = '$info[qishu]'")->row_array();
                $data['num'] = $user_shop_number['gonumber'];
                echo json_encode($data);exit;
            }
            
            if($q)
                echo '1';
            else
                echo '0';
        }
    }
    //获取最新商品记录
    function ajax_shop_done_json(){
        if($_POST){
            
            if(!isset($_POST['max_sincetime'])){
                echo json_encode(array("error"=>'1'));exit;
            }
            $max_sincetime = trim($_POST['max_sincetime']);
            $max_sincetime = $max_sincetime ? $max_sincetime : 0;
            $times = 180;
            if(!$times){$times = 1;}	

            //获取最新揭晓的商品,正在倒计时的商品
            $infos = $this->db->query("select qishu period,id shopId,thumb,title,zongrenshu zongNum,money price,q_end_time,end_time from `tan_go_shoplist` where `q_showtime` = 'Y' and `end_time` > $max_sincetime  order by `end_time` DESC")->result_array();			
            if(!$infos){
                echo json_encode(array("error"=>'1'));exit;
            }		
            foreach($infos as $key=>$info){//
                $q_time = substr($info['q_end_time'],0,10);
                $infos[$key]['times'] = $q_time-time();//计算剩余揭晓时间，单位‘秒’
                $infos[$key]['detail_url'] = web_url("lottery_finish/". encrypt_lottery_id($info['shopId']));
                $infos[$key]['shopId'] = encrypt_lottery_id($info['shopId']);
                unset($infos[$key]['q_end_time']);
            }
            echo json_encode(array("error"=>"0","listItems"=>$infos,"maxSeconds"=>$infos[0]['end_time']));exit;
        }
    }
    
    //最新揭晓页面数据
    function ajax_fetch_json(){
        $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;
        $records_per_page = 27;
        $totalCount = $this->db->query("select * from tan_go_shoplist where q_uid is not null order by end_time desc")->num_rows();
        $list = $this->db->query("select s.id shopid,s.title,s.thumb,s.zongrenshu,s.qishu,s.q_uid,s.q_end_time,s.q_showtime,s.end_time,s.q_user_code,u.nickname,u.head_img from tan_go_shoplist s left join tan_users_info u on u.user_id = s.q_uid where s.q_uid is not null order by s.end_time desc limit ".($pageIndex * $records_per_page).",$records_per_page")->result_array();
        foreach ($list as $key => $val){
            $q_time = substr($val['q_end_time'],0,10);
            $list[$key]['shopid'] = encrypt_lottery_id($val['shopid']);
            $list[$key]['lottery_url'] = web_url("lottery_finish/".encrypt_lottery_id($val['shopid']));
            if($q_time <= time()){//揭晓时间已过，更新数据
                $this->db->query("update `tan_go_shoplist` SET `q_showtime` = 'N' where `id` = '$val[shopid]' and `q_showtime` = 'Y' and `q_uid` is not null");
                //获奖用户本期总参与数
                $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$val[q_uid]' and `shopid` = '$val[shopid]' and `shopqishu` = '$val[qishu]'")->row_array();
                $user = array(
                    "uuid" => encrypt_user_id($val['q_uid']),
                    "luck_code" => $val['q_user_code'],
                    "num" => $user_shop_number['gonumber'],
                    "nickname" => $val['nickname'],
                    "head_img" => $val['head_img'],
                    "space_url" => web_url("u/".encrypt_user_id($val['q_uid'])),
                    "time" => $this->set_time_two($q_time)
                );
                $list[$key]['user'] = $user;
            }else{
                $list[$key]['user'] = array();
                $list[$key]['times'] = $q_time-time();
            }
            unset($list[$key]['q_uid']);unset($list[$key]['q_user_code']);unset($list[$key]['nickname']);unset($list[$key]['head_img']);
        }
        $result = array(
            "reqStatus" => true,
            "data" => array(
                "totalCount" => $totalCount ? $totalCount : 0,
                "pageIndex" => $pageIndex,
                "listItems" => $list,
            )
        );
        echo json_encode($result,JSON_HEX_TAG);die;
    }
    
    //获取往期中奖记录
    function ajax_fetch_period(){
        if($_POST){
            $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;
            $shopId = isset($_REQUEST['shopId']) ? trim($_REQUEST['shopId']) : 0;
            $shopId = decrypt_lottery_id($shopId);
            $records_per_page = 12;
            $where = "s.sid = $shopId and s.q_showtime = 'N' and s.q_uid is not null";
            
            $totalCount = $this->db->query("select s.* from tan_go_shoplist s where $where")->num_rows();
            $list = $this->db->query("select s.id shopId,s.qishu period,s.q_user_code luckCode,s.q_uid userId,u.nickname nickName,u.head_img headImg from tan_go_shoplist s left join tan_users_info u on u.user_id = s.q_uid where $where order by s.qishu desc limit ".($pageIndex * $records_per_page).",$records_per_page")->result_array();
            foreach ($list as $key=>$val){
                //中奖用户信息
                $record = $this->db->query("select time from tan_go_member_go_record where  uid = $val[userId] and shopid = $val[shopId] and shopqishu = $val[period] and goucode like '%$val[luckCode]%'  order by id desc limit 1")->row_array();
                $list[$key]['time'] = date("Y-m-d H:i:s",substr($record['time'],0,10)).substr($record['time'],10,13);
                //云购次数
                $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$val[userId]' and `shopid` = $val[shopId] and `shopqishu` = '$val[period]'")->row_array();
                $list[$key]['num'] = $user_shop_number['gonumber'];
                $list[$key]['lottery_url'] = web_url("lottery_finish/".encrypt_lottery_id($val['shopId']));
                $list[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['userId']));
                unset($list[$key]['shopId']);unset($list[$key]['userId']);
            }
            
            $result = array(
                "reqStatus" => true,
                "data" => array(
                    "totalCount" => $totalCount ? $totalCount : 0,
                    "pageIndex" => $pageIndex,
                    "listItems" => $list,
                )
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    
    function ajax_fetch_buy_list(){
        if($_POST){
            $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;
            $shopId = isset($_REQUEST['shopId']) ? trim($_REQUEST['shopId']) : 0;
            $shopId = decrypt_lottery_id($shopId);
            
            $item = $this->go_shoplist_model->get_shoplist_one(array("id"=>$shopId));
            $records_per_page = 12;
            
            $where = "r.shopid = $shopId and r.shopqishu = $item[qishu]";
            $totalCount = $this->db->query("select r.* from tan_go_member_go_record r where $where")->num_rows();
            $list = $this->db->query("select r.id,r.gonumber num,r.ip,r.time,u.nickname nickName,u.head_img headImg,r.uid userId from tan_go_member_go_record r left join tan_users_info u on u.user_id = r.uid where $where order by r.id desc limit ".($pageIndex * $records_per_page).",$records_per_page")->result_array();
            foreach ($list as $key=>$val){
                $time = substr($val['time'],0,10);
                $list[$key]['time'] = date("Y-m-d H:i:s",$time).substr($val['time'],10,13);
                $list[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['userId']));
                $list[$key]['record_id'] = encrypt_lottery_record_id($val['id']);
                unset($list[$key]['userId']);unset($list[$key]['id']);
            }
            
            $result = array(
                "reqStatus" => true,
                "data" => array(
                    "totalCount" => $totalCount ? $totalCount : 0,
                    "pageIndex" => $pageIndex,
                    "listItems" => $list,
                )
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    //获取用户夺宝记录号码
    function ajax_buy_code(){
        if($_POST){
            $record_id = isset($_POST['recordId']) ? trim($_POST['recordId']) : 0;
            $record_id = decrypt_lottery_record_id($record_id);
            $record = $this->db->query("select r.goucode from tan_go_member_go_record r where r.id = $record_id")->row_array();
            $code_arr = explode(",", $record['goucode']);
            $html = "";
            foreach ($code_arr as $key=>$code){
                $html .= "<p>$code</p>";
            }
            
            $result = array(
                "reqStatus" => true,
                "codeStr" => $html,
                "codeNum" => count($code_arr),
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    
    //获取用户在本期全部夺宝记录号码
    function ajax_user_code(){
        if($_POST){
            $shop_id = isset($_POST['shopId']) ? trim($_POST['shopId']) : 0;
            $shop_id = decrypt_lottery_id($shop_id);
            $shop = $this->db->query("select q_uid,qishu,q_user_code from tan_go_shoplist where id = $shop_id")->row_array();
            $records = $this->db->query("select goucode from tan_go_member_go_record where shopid = $shop_id and shopqishu = $shop[qishu] and uid = $shop[q_uid] order by id desc")->result_array();
            $html = "";
            $count = 0;
            foreach ($records as $key=>$val){
                $code_arr = explode(",", $val['goucode']);
                foreach ($code_arr as $code){
                    $count ++;
                    if($code == $shop['q_user_code']){
                        $html .= "<p class='error'>$code</p>";
                    }else{
                        $html .= "<p>$code</p>";
                    }
                }
            }
            
            $result = array(
                "reqStatus" => true,
                "codeStr" => $html,
                "codeNum" => $count,
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    /*********ajax异步调用区end*********/
    
    /*********私有函数区start***********/
    //获取推荐产品
    private function get_remmond_goods($is_no_goods_id,$is_no_goods_sid){
        $recommend_goods = $this->db->query("select id,title,thumb,zongrenshu,canyurenshu,shenyurenshu from tan_go_shoplist where id in(select id from tan_go_shoplist where id != $is_no_goods_id and sid != $is_no_goods_sid and pos > 0 and q_uid is null) limit 2")->result_array();
        if($recommend_goods){
            foreach ($recommend_goods as $key=>$val){
                $recommend_goods[$key]["lottery_url"] = web_url("lottery/".encrypt_lottery_id($val['id']));
            }
        }
        return $recommend_goods;
    }
    //获取全部夺宝商品
    private function get_all_shops_list(){
        $where = array();
        $where['q_uid'] = null;
        $list = $this->db->select("id,title,thumb,zongrenshu,canyurenshu,shenyurenshu")->from("go_shoplist")->where($where)->order_by("shenyurenshu ASC")->limit(20,0)->get()->result_array();
        foreach ($list as $key=>$val){
            $list[$key]['lottery_url'] = web_url("lottery/".encrypt_lottery_id($val['id']));
        }
        return $list;
    }
    //相关问答
    private function relative_wenda(){
        $list = $this->db->query("select w.id,w.questioner_id,w.summary,w.title,u.head_img from tan_bbs_wenda w left join tan_users_info u on u.user_id = w.questioner_id where tags_name like '%溜溜心愿%' order by w.id desc limit 3")->result_array();
        foreach ($list as $key=>$val){
            $list[$key]['wenda_url'] = web_url("wenda/".encrypt_wenda_id($val['id']));
            $list[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['questioner_id']));
        }
        return $list;
    }
    //相关晒单文章
    private  function relative_article(){
        $list = $this->db->query("select a.id,a.authorid,a.summary,a.thumb,a.title,a.readnum,u.head_img,u.nickname from tan_bbs_article a left join tan_users_info u on u.user_id = a.authorid where a.tags_name like '%溜溜夺宝%' order by a.id desc limit 12")->result_array();
        foreach ($list as $key=>$val){
            $list[$key]['detial_url'] = web_url("p/".  encrypt_article_id($val['id']));
            $list[$key]['space_url'] = web_url("u/".  encrypt_user_id($val['authorid']));
            $list[$key]['summary'] = mb_strcut($val['summary'], 0,34,"utf-8")."...";
        }
        return $list;
    }
    //用户夺宝记录
    private function get_user_duoing_list($max_id){
        if($max_id){
            $and_where = " where r.id > $max_id";
            $limit = "";
        }else{
            $limit = " limit 6";
        }
        $list = $this->db->query("select r.id,r.uid,r.shopid,r.time,r.gonumber num,s.title,u.head_img,u.nickname from tan_go_member_go_record r left join tan_go_shoplist s on s.id = r.shopid left join tan_users_info u on u.user_id = r.uid $and_where order by r.id desc $limit")->result_array();
        foreach ($list as $key => $val){
            $list[$key]['title'] = $val['title'];
            $list[$key]['buy_id'] = encrypt_lottery_record_id($val['id']);
            $list[$key]['time'] = $this->set_time_three(substr($val['time'],0,10));
            $list[$key]['space_url'] = web_url("u/".encrypt_user_id($val['uid']));
            $list[$key]['lottery_url'] = web_url("lottery/".  encrypt_lottery_id($val['shopid']));
            unset($list[$key]['id']);
            unset($list[$key]['uid']);
            unset($list[$key]['shopid']);
        }
        return $list;
    }
    //获取即将揭晓的商品
    private function get_duoed_list($max_id){
        $list = $this->db->query("select s.id shopid,s.title,s.thumb,s.zongrenshu,s.qishu,s.q_uid,s.q_end_time,s.q_showtime,s.end_time,s.q_user_code,u.nickname,u.head_img from tan_go_shoplist s left join tan_users_info u on u.user_id = s.q_uid where s.q_uid is not null order by s.q_end_time desc limit 3")->result_array();
        foreach ($list as $key => $val){
            $q_time = substr($val['q_end_time'],0,10);
            
            $list[$key]['shopid'] = encrypt_lottery_id($val['shopid']);
            $list[$key]['lottery_url'] = web_url("lottery_finish/".encrypt_lottery_id($val['shopid']));
            if($q_time <= time()){//揭晓时间已过，更新数据
                $this->db->query("update `tan_go_shoplist` SET `q_showtime` = 'N' where `id` = '$val[shopid]' and `q_showtime` = 'Y' and `q_uid` is not null");
                //获奖用户本期总参与数
                $user_shop_number = $this->db->query("select sum(gonumber) as gonumber from `tan_go_member_go_record` where `uid`= '$val[q_uid]' and `shopid` = '$val[shopid]' and `shopqishu` = '$val[qishu]'")->row_array();
                $user = array(
                    "uuid" => encrypt_user_id($val['q_uid']),
                    "luck_code" => $val['q_user_code'],
                    "num" => $user_shop_number['gonumber'],
                    "nickname" => $val['nickname'],
                    "head_img" => $val['head_img'],
                    "space_url" => web_url("u/".encrypt_user_id($val['q_uid'])),
                    "time" => $this->set_time_two($q_time)
                );
                $list[$key]['user'] = $user;
            }else{
                $list[$key]['user'] = array();
                $list[$key]['times'] = $q_time-time();
            }
            unset($list[$key]['q_uid']);unset($list[$key]['q_user_code']);unset($list[$key]['nickname']);unset($list[$key]['head_img']);
        }
        return $list;
    }
    
    /*********私有函数区end***********/
}